package cn.lkp.mall.ware.service.impl;

import cn.lkp.common.expection.NoStockException;
import cn.lkp.common.to.mq.StockDetailTo;
import cn.lkp.common.to.mq.StockLockedTo;
import cn.lkp.common.utils.R;
import cn.lkp.mall.ware.enums.OrderStatusEnum;
import cn.lkp.mall.ware.entity.WareOrderTaskDetailEntity;
import cn.lkp.mall.ware.entity.WareOrderTaskEntity;
import cn.lkp.mall.ware.feign.OrderFeign;
import cn.lkp.mall.ware.feign.ProductFeignService;
import cn.lkp.mall.ware.service.WareOrderTaskDetailService;
import cn.lkp.mall.ware.service.WareOrderTaskService;
import cn.lkp.mall.ware.to.OrderTo;
import cn.lkp.mall.ware.vo.OrderItemVo;
import cn.lkp.mall.ware.vo.OrderVo;
import cn.lkp.mall.ware.vo.SkuHasStockVo;
import cn.lkp.mall.ware.vo.WareSkuLockVo;
import com.alibaba.fastjson.TypeReference;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lkp.common.utils.PageUtils;
import cn.lkp.common.utils.Query;

import cn.lkp.mall.ware.dao.WareSkuDao;
import cn.lkp.mall.ware.entity.WareSkuEntity;
import cn.lkp.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    OrderFeign orderFeign;
    @Autowired
    WareSkuDao wareSkuDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //
        List<WareSkuEntity> entities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //使用try...catch防止因远程调用服务异常导致整个事务回滚
            try{
                //调用远程服务查询skuName
                R info = productFeignService.info(skuId);
                //skuInfo是一个SkuInfoEntity,他有skuName属性
                Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if(info.getCode()==0){
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                }
            }catch (Exception e){
            }
            this.baseMapper.insert(wareSkuEntity);
        }else {
            this.baseMapper.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的总库存量
            // 数据库中stock_locked不能为null，否则SUM(stock-stock_locked)为null
            //SELECT SUM(stock-stock_locked) FROM `wms_ware_sku` WHERE sku_id = 1
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:(count>0));
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        //库存解锁
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新工作单的状态
        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
        taskDetailEntity.setId(taskDetailId);
        //变为已解锁
        taskDetailEntity.setLockStatus(2);
        //更新数据库
        wareOrderTaskDetailService.updateById(taskDetailEntity);
    }

    /**
     * 为某个订单锁定库存
     * 默认只要是运行时异常，都会回滚
     * (rollbackFor = NoStockException.class)
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        /**
         * 保存库存工作单详情信息
         * 追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);
        //1、按照下单的收货地址，找到一个就近仓库，锁定库存
        //2、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> skuWareHasStockList = locks.stream().map((lock) -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(lock.getSkuId());
            skuWareHasStock.setNum(lock.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasSkuStock(lock.getSkuId());
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());
        Boolean allLock = true;
        //2、锁定库存
        for (SkuWareHasStock skuWareHasStock : skuWareHasStockList) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if(StringUtils.isEmpty(wareIds)){
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所以就不用解锁
            for (Long wareId : wareIds) {
                //锁定成功就返回1，失败就返回0
                Long count = this.baseMapper.lockSkuStock(skuId,wareId,skuWareHasStock.getNum());
                if(count == 1){
                    skuStocked = true;
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .skuName("")
                            .skuNum(skuWareHasStock.getNum())
                            .taskId(wareOrderTaskEntity.getId())
                            .wareId(wareId)
                            .lockStatus(1)
                            .build();
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    //告诉MQ锁定成功
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    //wareOrderTaskEntity.getId()和wareOrderTaskDetailEntity.getTaskId()相同
                    stockLockedTo.setId(wareOrderTaskEntity.getId());

                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity,stockDetailTo);
                    stockLockedTo.setStockDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if(skuStocked == false){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        //3、肯定全部都是锁定成功的
        return true;
    }

    @Override
    public void unLockStock(StockLockedTo to) {
        //库存工作单的id
        StockDetailTo stockDetailTo = to.getStockDetailTo();
        Long detailId= stockDetailTo.getId();
        /**
         * 解锁
         * 1、查询数据库关于这个订单锁定库存信息
         *   有：证明库存锁定成功了
         *      解锁：订单状况
         *          1、没有这个订单，必须解锁库存
         *          2、有这个订单，不一定解锁库存
         *              订单状态：已取消：解锁库存
         *                      已支付：不能解锁库存
         */
        WareOrderTaskDetailEntity taskDetailInfo = wareOrderTaskDetailService.getById(detailId);
        if(taskDetailInfo!=null){
            //解锁
            //查出wms_ware_order_task工作单的信息
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            //订单号
            String orderSn = taskEntity.getOrderSn();
            //远程查询订单信息,因为订单模块中加入了登陆拦截器，所以需要在拦截器中放行此方法
            R orderData = orderFeign.getOrderStatus(orderSn);
            if(orderData.getCode()==0){
                //订单数据返回成功
                OrderVo orderInfo = orderData.getData(new TypeReference<OrderVo>() {
                });
                //判断订单状态是否已取消或者订单不存在
                if(orderInfo == null || orderInfo.getStatus()== OrderStatusEnum.CANCLED.getCode()){
                    //订单已被取消，才能解锁库存
                    if(taskDetailInfo.getLockStatus()==1){
                        //当前库存工作单详情状态1，已锁定，但是未解锁才可以解锁
                        unLockStock(stockDetailTo.getSkuId(), stockDetailTo.getWareId(), stockDetailTo.getSkuNum(), detailId);
                    }
                }
            }else{
                //远程调用服务失败
                throw new RuntimeException("远程调用服务失败");
            }
        }else{
            //查询数据库关于这个订单锁定库存信息,库存锁定失败了，库存回滚了，无需解锁
        }
    }
    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unLockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        Long id = orderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : list) {
                unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}